package com.njcb.game.web.controller;

import com.njcb.ams.portal.SysBaseDefine;
import com.njcb.ams.support.exception.ExceptionUtil;
import com.njcb.ams.util.AmsAssert;
import com.njcb.ams.util.AmsUtils;
import com.njcb.ams.web.controller.common.FileUpDownloadController;
import com.njcb.game.repository.dao.GameRegisterDAO;
import com.njcb.game.repository.entity.GameRegister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.Map;

/**
 * @author LOONG
 */
@RestController
public class FileDownloadController {
    private static final Logger logger = LoggerFactory.getLogger(FileUpDownloadController.class);

    @Autowired
    private GameRegisterDAO gameRegisterDAO;

    /**
     * 文件保存位置
     */
    public static String CURRENT_FILE_PATH = SysBaseDefine.SYS_FILE_TMP_PATH;
    private String contentDisposition = new String();


    /**
     * 文件下载接口
     *
     * @param request
     * @param response
     * @param paramMap
     * @throws Exception
     */
    @RequestMapping(value = "gamefile")
    @ResponseBody
    public void downloadfile(HttpServletRequest request, HttpServletResponse response,
                             @RequestBody(required = false) Map paramMap) throws Exception {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache,no-store,max-age=0");
        response.setDateHeader("Expires", 1);
        String fileName = "";
        if (AmsUtils.isNotNull(paramMap)) {
            fileName = (String) paramMap.get("fileName");
        }
        if (AmsUtils.isNull(fileName)) {
            fileName = request.getParameter("fileName");
        }
        if (AmsUtils.isNull(fileName)) {
            ExceptionUtil.throwAppException("请添加参数?fileName=token");
        } else {
            GameRegister gameRegister = gameRegisterDAO.selectByToken(fileName);
            AmsAssert.notNull(gameRegister, "token[" + fileName + "]不存在");
        }
        response.setHeader("Content-Disposition", this.contentDisposition + " filename=" + fileName);
        // 复制缓冲区的大小
        int paramInt = 65000;
        ServletOutputStream os = response.getOutputStream();
        File localFile = new File(CURRENT_FILE_PATH + fileName);
        if (!localFile.exists()) {
            ExceptionUtil.throwAppException("文件[" + fileName + "]不存在");
        }
        FileInputStream localFileInputStream = new FileInputStream(localFile);
        // 下载的文件长度
        long fileLength = localFile.length();
        byte[] arrayOfByte = new byte[paramInt];

        this.contentDisposition = ((this.contentDisposition == null) ? "attachment;" : this.contentDisposition);
        int i = 0;
        int j = 0;
        while (j < fileLength) {
            i = localFileInputStream.read(arrayOfByte, 0, paramInt);
            j += i;
            os.write(arrayOfByte, 0, i);
        }
        os.flush();
        os.close();
        logger.info("用户在客户端[{}]下载了文件[{}]", request.getRemoteAddr(), fileName);
        response.setContentLength((int) fileLength);
        response.flushBuffer();
        localFileInputStream.close();
    }
}
